<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="订单编号" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="支付单号" prop="paymentNo">
        <el-input v-model="formData.paymentNo" placeholder="请输入支付单号" />
      </el-form-item>
      <el-form-item label="平台支付ID" prop="platformPaymentId">
        <el-input v-model="formData.platformPaymentId" placeholder="请输入平台支付ID" />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-input v-model="formData.paymentMethod" placeholder="请输入支付方式" />
      </el-form-item>
      <el-form-item label="支付渠道" prop="paymentChannel">
        <el-input v-model="formData.paymentChannel" placeholder="请输入支付渠道" />
      </el-form-item>
      <el-form-item label="支付服务商" prop="paymentProvider">
        <el-input v-model="formData.paymentProvider" placeholder="请输入支付服务商" />
      </el-form-item>
      <el-form-item label="支付类型" prop="paymentType">
        <el-select v-model="formData.paymentType" placeholder="请选择支付类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_PAYMENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付金额" prop="paymentAmount">
        <el-input v-model="formData.paymentAmount" placeholder="请输入支付金额" />
      </el-form-item>
      <el-form-item label="支付货币" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入支付货币" />
      </el-form-item>
      <el-form-item label="汇率" prop="exchangeRate">
        <el-input v-model="formData.exchangeRate" placeholder="请输入汇率" />
      </el-form-item>
      <el-form-item label="基础货币金额" prop="baseAmount">
        <el-input v-model="formData.baseAmount" placeholder="请输入基础货币金额" />
      </el-form-item>
      <el-form-item label="手续费" prop="feeAmount">
        <el-input v-model="formData.feeAmount" placeholder="请输入手续费" />
      </el-form-item>
      <el-form-item label="网关费用" prop="gatewayFee">
        <el-input v-model="formData.gatewayFee" placeholder="请输入网关费用" />
      </el-form-item>
      <el-form-item label="处理费用" prop="processingFee">
        <el-input v-model="formData.processingFee" placeholder="请输入处理费用" />
      </el-form-item>
      <el-form-item label="净收金额" prop="netAmount">
        <el-input v-model="formData.netAmount" placeholder="请输入净收金额" />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-radio-group v-model="formData.paymentStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_PAYMENT_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="交易ID" prop="transactionId">
        <el-input v-model="formData.transactionId" placeholder="请输入交易ID" />
      </el-form-item>
      <el-form-item label="授权码" prop="authorizationCode">
        <el-input v-model="formData.authorizationCode" placeholder="请输入授权码" />
      </el-form-item>
      <el-form-item label="参考号" prop="referenceNo">
        <el-input v-model="formData.referenceNo" placeholder="请输入参考号" />
      </el-form-item>
      <el-form-item label="支付时间" prop="paymentTime">
        <el-date-picker
          v-model="formData.paymentTime"
          type="date"
          value-format="x"
          placeholder="选择支付时间"
        />
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="date"
          value-format="x"
          placeholder="选择过期时间"
        />
      </el-form-item>
      <el-form-item label="回调时间" prop="callbackTime">
        <el-date-picker
          v-model="formData.callbackTime"
          type="date"
          value-format="x"
          placeholder="选择回调时间"
        />
      </el-form-item>
      <el-form-item label="回调数据JSON" prop="callbackData">
        <el-input v-model="formData.callbackData" placeholder="请输入回调数据JSON" />
      </el-form-item>
      <el-form-item label="风险评分" prop="riskScore">
        <el-input v-model="formData.riskScore" placeholder="请输入风险评分" />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="反欺诈检查结果JSON" prop="fraudCheckResult">
        <el-input v-model="formData.fraudCheckResult" placeholder="请输入反欺诈检查结果JSON" />
      </el-form-item>
      <el-form-item label="支付信息JSON" prop="paymentInfo">
        <el-input v-model="formData.paymentInfo" placeholder="请输入支付信息JSON" />
      </el-form-item>
      <el-form-item label="错误代码" prop="errorCode">
        <el-input v-model="formData.errorCode" placeholder="请输入错误代码" />
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMessage">
        <el-input v-model="formData.errorMessage" placeholder="请输入错误信息" />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input v-model="formData.retryCount" placeholder="请输入重试次数" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderPaymentApi, OrderPaymentVO } from '@/api/crossborder/orderpayment'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** 跨境电商订单支付 表单 */
defineOptions({ name: 'OrderPaymentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderId: undefined,
  orderNo: undefined,
  paymentNo: undefined,
  platformPaymentId: undefined,
  paymentMethod: undefined,
  paymentChannel: undefined,
  paymentProvider: undefined,
  paymentType: undefined,
  paymentAmount: undefined,
  currencyCode: undefined,
  exchangeRate: undefined,
  baseAmount: undefined,
  feeAmount: undefined,
  gatewayFee: undefined,
  processingFee: undefined,
  netAmount: undefined,
  paymentStatus: undefined,
  transactionId: undefined,
  authorizationCode: undefined,
  referenceNo: undefined,
  paymentTime: undefined,
  expireTime: undefined,
  callbackTime: undefined,
  callbackData: undefined,
  riskScore: undefined,
  riskLevel: undefined,
  fraudCheckResult: undefined,
  paymentInfo: undefined,
  errorCode: undefined,
  errorMessage: undefined,
  retryCount: undefined,
  remark: undefined,
})
const formRules = reactive({
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  paymentNo: [{ required: true, message: '支付单号不能为空', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
  paymentType: [{ required: true, message: '支付类型（1全额支付 2部分支付 3分期支付）不能为空', trigger: 'change' }],
  paymentAmount: [{ required: true, message: '支付金额不能为空', trigger: 'blur' }],
  currencyCode: [{ required: true, message: '支付货币不能为空', trigger: 'blur' }],
  feeAmount: [{ required: true, message: '手续费不能为空', trigger: 'blur' }],
  gatewayFee: [{ required: true, message: '网关费用不能为空', trigger: 'blur' }],
  processingFee: [{ required: true, message: '处理费用不能为空', trigger: 'blur' }],
  netAmount: [{ required: true, message: '净收金额不能为空', trigger: 'blur' }],
  paymentStatus: [{ required: true, message: '支付状态（10待支付 20支付中 30支付成功 40支付失败 50已退款 60部分退款）不能为空', trigger: 'blur' }],
  retryCount: [{ required: true, message: '重试次数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderPaymentApi.getOrderPayment(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderPaymentVO
    if (formType.value === 'create') {
      await OrderPaymentApi.createOrderPayment(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderPaymentApi.updateOrderPayment(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderId: undefined,
    orderNo: undefined,
    paymentNo: undefined,
    platformPaymentId: undefined,
    paymentMethod: undefined,
    paymentChannel: undefined,
    paymentProvider: undefined,
    paymentType: undefined,
    paymentAmount: undefined,
    currencyCode: undefined,
    exchangeRate: undefined,
    baseAmount: undefined,
    feeAmount: undefined,
    gatewayFee: undefined,
    processingFee: undefined,
    netAmount: undefined,
    paymentStatus: undefined,
    transactionId: undefined,
    authorizationCode: undefined,
    referenceNo: undefined,
    paymentTime: undefined,
    expireTime: undefined,
    callbackTime: undefined,
    callbackData: undefined,
    riskScore: undefined,
    riskLevel: undefined,
    fraudCheckResult: undefined,
    paymentInfo: undefined,
    errorCode: undefined,
    errorMessage: undefined,
    retryCount: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>